#include "comm-func.h"
#include <random>
#include <chrono>
#include <string.h>
#include <iconv.h>
#include <iostream>
#include <sstream>
#include <iomanip>

std::string generate_numeric_tag()
{
    // 使用时间作为随机种子
    unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
    std::mt19937 generator(seed);

    // 定义分布：1000000000到9999999999（10位数字）
    std::uniform_int_distribution<long long> distribution(1000000000, 9999999999);

    return std::to_string(distribution(generator));
}

std::string FindField(const char* buf, const char* start, const char *end ,int bufSize)
{
    if(bufSize <=0 ){
        bufSize = strlen(buf);
    }
    const char *msg_start = buf, *msg_end = buf + bufSize;
    int len = 0;
    if (start != NULL) {
        len = strlen(start);
        msg_start = strstr(buf, start);
    }
    if (msg_start == NULL) {
        return "";
    }
    msg_start += len;
    if (end != NULL) {
        msg_end = strstr(msg_start, end);
        if (msg_end == NULL) {
            return "";
        }
    }
    return std::string(msg_start, msg_end);
}

// 辅助函数：GB2312转UTF-8
std::string gb2312_to_utf8(const std::string& gb2312_str)
{
    if (gb2312_str.empty()) return "";

    iconv_t cd = iconv_open("UTF-8", "GB2312");
    if (cd == (iconv_t)-1) {
        fprintf(stdout, "Error: Failed to open iconv conversion descriptor\n");
        return gb2312_str;
    }

    size_t in_bytes = gb2312_str.size();
    size_t out_bytes = in_bytes * 4; // 预留足够空间
    char* in_buf = const_cast<char*>(gb2312_str.data());
    char* out_buf = new char[out_bytes];
    char* out_ptr = out_buf;

    memset(out_buf, 0, out_bytes);

    size_t result = iconv(cd, &in_buf, &in_bytes, &out_ptr, &out_bytes);
    if (result == (size_t)-1) {
        fprintf(stdout, "Error: iconv conversion failed\n");;
        delete[] out_buf;

        iconv_close(cd);
        return gb2312_str;
    }

    std::string utf8_str(out_buf, out_ptr - out_buf);
    delete[] out_buf;
    iconv_close(cd);
    return utf8_str;
}

std::string int_to_hex(int num)
{
    std::stringstream ss;
    ss << std::hex << std::uppercase << num; // 转换为16进制格式
    return ss.str();
}
